Ext.define('Usws.controller.Channel', {
    extend: 'Ext.app.Controller',
    stores:['Channel', 'ChannelLevel', 'DomainDict', 'ChannelRelateCat', 'ChannelVideoAdd','ChannelVideoList'],
    refs: [
   		   {
               ref: 'contentPanel',
               selector: 'contentPanel'
           }
    ],
    
    init: function() {
    	this.control({
            'Channel-Grid actioncolumn':{
            	itemclick: this.actionColumnOptChannel
             },
             
             'ChannelVideoList-Grid actioncolumn':{
            	itemclick: this.actionColumnOptChannelVideo 
             },
             
             'ChannelVideoList-Grid button[action=delete]':{
             	click: this.deleteMoreChannelVideo 
              },
             
            'Channel-Grid button[action=add]': {
                 click: this.addChannel
             },
            'ChannelVideoAdd-Grid button[action=add]': {
            	click: this.addChannelVideo
            },
             'Channel-Edit button[action=save]': {
                 click: this.updateChannel
             },
             '#uploadChannelPic': {
            	 change: this.uploadChannelPic
             },
             '#uploadPlatePic': {
            	 change: this.uploadChannelPlatePic
             },
             '#uiType': {
            	 change: this.changeChannelPlate
             },
             '#channel_videoType radio':{
            	 change:this.changeChannelVideoType
             },
             '#targetRoleCheckBoxs checkboxfield':{
            	 change:this.changeChannelTargetRole
             }
        });
    },
    
    /**
     * actioncolumn opt
     */
    actionColumnOptChannel: function(column, view, rowIndex, colIndex, item, e, record) {
    	var parentNode = record.parentNode;
    	var exchangeNode;
    	if(item.action === 'upTop') {
    		/*
    		 * get firstChild node
    		 */
    		exchangeNode = parentNode.firstChild;
    	} else if(item.action === 'up') {
    		/*
    		 * get previoussibling node
    		 */
    		exchangeNode = record.previousSibling;
    	} else if(item.action === 'downTail') {
    		/*
    		 * get lastChild node
    		 */
    		exchangeNode = parentNode.lastChild;
    	} else if(item.action === 'down') {
    		/*
    		 * get nextsibling node
    		 */
    		exchangeNode = record.nextSibling;
    	}
    	
    	/*
    	 * if it is move opt, then do exchange
    	 */
    	if(item.action=== 'upTop' || item.action === 'up' || item.action === 'downTail' || item.action === 'down') {
    		 var ids = [];
    		 ids.push(record.get('uid'));  
    		 ids.push(exchangeNode.get('uid'));  
    		 
	         Ext.Ajax.request({  
	             url:'/channel/ajaxExchangeChannelPosition.action',  
	             params:{uids:ids.join(",")},
	             method:'POST',  
	             timeout:2000,  
	             success:function(response,opts){  
	             	if(response) {
	             		var tempSeqNum = exchangeNode.get('seqNum');
	    	    		exchangeNode.set('seqNum', record.get('seqNum'));
	    	    		record.set('seqNum', tempSeqNum);
	    	    		/*
	    	    		 * thoes exchange nodes restart sort
	    	    		 */
	    	    		parentNode.sort(function(record, exchangeNode) {
	    	    			return record.get('seqNum') - exchangeNode.get('seqNum');
	    	    		});
	             	} else {
	             		
	             	}
	             }  
	         }); 
    	} else if(item.action === 'edit') {
    		/*
    		 * edit channel
    		 */
    		this.editChannel(record);
    	} else if(item.action === 'delete') {
    		/*
    		 * delete channel
    		 */
    		this.deleteChannel(record);
    	} else if(item.action === 'addVedio') {
    		this.listAddChannelVideo(record);
    	} else if(item.action === 'listVedio') {
    		this.listChannelVideo(record);
    	}
    },
    
    addChannel: function(button) {
   	    this.initChannel();
   },
   
   initChannel:function() {
	   var view = Ext.widget('Channel-Edit');
	   
       /*
        * default public channel checked
        */
	   Ext.getCmp('checkBox_public').setValue(true);
       
       /*
        * load channel level
        */
       var channelLevelStore = this.getChannelLevelStore();
	   channelLevelStore.load();
	   
	   /*
	    * load channel plate
	    */
       var domainDictStore = this.getDomainDictStore();
       domainDictStore.on('beforeload', function (store, options) {
           var new_params = {domain: 'CHANNEL_PLATE'};
           Ext.apply(store.proxy.extraParams, new_params);
        });
       domainDictStore.load();
       
       /*
        * load relate cat
        */
       var channelRelateCatStore = this.getChannelRelateCatStore();
       channelRelateCatStore.on('beforeload', function (store, options) {
           var new_params = {'channel.relateCat': ''};
           Ext.apply(store.proxy.extraParams, new_params);
        });
       channelRelateCatStore.load();
       
       /*
        * default normal video type checked
        */
       Ext.getCmp('checkBox_normal').setValue(true);
       var video = Ext.get('video_type3');
       var metting = Ext.get('video_type4');
       video.hide();
       metting.hide();
       view.doLayout();
       view.center();
   },
    
    editChannel: function(record) {
       var view = Ext.widget('Channel-Edit');
    	
	   var channelPictureURL = record.get('channelPictureURL');
	   if(channelPictureURL) {
		   Ext.getCmp('previewChannelPic').body.update('<img src="'+channelPictureURL + '?t='+new Date().getTime()+'" width="80" height="60"/>');
	   }
	   
	   var platePicture = record.get('platePicture');
	   if(platePicture) {
		   Ext.getCmp('previewPlatePic').body.update('<img src="'+platePicture + '?t='+new Date().getTime()+'" width="80" height="60"/>');
	   }
    	
     	var parentUid = record.get('parentUid');
        var channelLevelStore = this.getChannelLevelStore();
//      channelLevelStore.on('beforeload', function (store, options) {
//            var new_params = {parentUid: parentUid};
//            Ext.apply(store.proxy.extraParams, new_params);
//      });
	    channelLevelStore.load({parentUid: parentUid});
        
	    var domainDictStore = this.getDomainDictStore();
	    domainDictStore.on('beforeload', function (store, options) {
	           var new_params = {domain: 'CHANNEL_PLATE'};
	           Ext.apply(store.proxy.extraParams, new_params);
	        });
	    domainDictStore.load();
	    
        var checkRelateCat = record.get("relateCat");
        //Ext.getCmp('channelRelateCatTree').removeAll(true);
        //channelRelateCatStore.load();
        
        //channelRelateCatStore.findRecord("catUid",)
        var channelRelateCatStore = this.getChannelRelateCatStore();
        channelRelateCatStore.on('beforeload', function (store, options) {
            var new_params = {'channel.relateCat': checkRelateCat};
            Ext.apply(store.proxy.extraParams, new_params);
         });
        channelRelateCatStore.load();
//        if(checkRelateCat) {
//        	var channelRelateCatStore = this.getChannelRelateCatStore();
//        	alert(Ext.getDisplayName(channelRelateCatStore) + channelRelateCatStore.getModifiedRecords().length);
//        	alert("--------------" + channelRelateCatStore.getUpdatedRecords().length);
//        	Ext.Array.each(channelRelateCatStore.getNewRecords(), function(record){
//        		alert(record.get("name"));
//        	});
//        	Ext.Array.each(checkRelateCat.split(","), function(value, index, catItSelf) {
//        	    alert(value +"-----"+index+"---"+catItSelf);
//        	    //channelRelateCatStore.findRecord("catUid",value).set("checked",true);
//        	});
//        	//checkRelateCat.split(",").each
//        }
       // alert(checkRelateCat.split(","));
        
        var targetRole = record.get('targetRole');
        var uiTypeSet = Ext.get('uiTypeSet');
 	    var plateDistribution = Ext.get('plateDistribution');
 	    var previewPlatePicPanel = Ext.get('previewPlatePicPanel');
 	    
 	    uiTypeSet.hide();
	    plateDistribution.hide();
	    previewPlatePicPanel.hide();
	    if((targetRole&4) === 4) {
           Ext.getCmp('checkBox_public').setValue(true);
        } 
        if((targetRole&1) === 1) {
           Ext.getCmp('checkBox_student').setValue(true);
        } 
        if((targetRole&2) === 2) {
           Ext.getCmp('checkBox_parent').setValue(true);
        }
        if((targetRole&8) === 8) {
           Ext.getCmp('checkBox_teacher').setValue(true);
        } 
        
        var channelTypeDsid = record.get('channelTypeDsid');
        var video = Ext.get('video_type3');
        var metting = Ext.get('video_type4');
        
        if(channelTypeDsid === 3) {
        	Ext.getCmp('checkBox_video').setValue(true);
        	metting.hide();
        	
        	var videoQuality = record.get('videoQuality');
        	var videoFrom = record.get('videoFrom');
        	
        	if((videoQuality&1) === 1) {
        		 Ext.getCmp('videoQuality1').setValue(true);
        	}
        	if((videoQuality&2) === 2) {
        		 Ext.getCmp('videoQuality2').setValue(true);
        	}
        	
        	if((videoFrom&1) === 1) {
	       		 Ext.getCmp('videoFrom1').setValue(true);
	       	}
	       	if((videoFrom&2) === 2) {
	       		 Ext.getCmp('videoFrom2').setValue(true);
	       	}
        	
        } else if(channelTypeDsid === 4) {
        	Ext.getCmp('checkBox_metting').setValue(true);
        	video.hide();
        	var mettingType = record.get('mettingType');
        	var mettingStatus = record.get('mettingStatus');
        	
        	if((mettingType&1) === 1) {
        		 Ext.getCmp('mettingType1').setValue(true);
        	}
        	if((mettingType&2) === 2) {
        		 Ext.getCmp('mettingType2').setValue(true);
        	}
        	
        	if((mettingType&4) === 4) {
	       		 Ext.getCmp('mettingType4').setValue(true);
	       	}
	       	if((mettingType&8) === 8) {
	       		 Ext.getCmp('mettingType8').setValue(true);
	       	}
	       	
	     	if((mettingStatus&1) === 1) {
	       		 Ext.getCmp('mettingStatus1').setValue(true);
	       	}
	     	if((mettingStatus&2) === 2) {
	       		 Ext.getCmp('mettingStatus2').setValue(true);
	       	}
	     	if((mettingStatus&4) === 4) {
	       		 Ext.getCmp('mettingStatus4').setValue(true);
	       	}
        } else {
        	video.hide();
        	metting.hide();
        	if(channelTypeDsid === 1) {
            	Ext.getCmp('checkBox_normal').setValue(true);
            } else if(channelTypeDsid === 2) {
            	Ext.getCmp('checkBox_function').setValue(true);
            } 
        }
        view.doLayout();
        view.center();
        
        view.down('form').loadRecord(record);
   },
   
   updateChannel: function(button) {
	   var relateCatrecords = Ext.getCmp('channelRelateCatTree').getChecked(),
	   catUids = [];
	   Ext.Array.each(relateCatrecords, function(rec){
		   catUids.push(rec.get('catUid'));
	   });
	   
	   //var targetRoleRecords = Ext.getCmp('targetRoleCheckBoxs').items.getChecked();
	   var targetRole;
	   Ext.getCmp('targetRoleCheckBoxs').items.each(function(rec){
		   if(rec.checked) {
			   targetRole |= rec.inputValue;
		   }
	   });
	   
	   var videoQuality;
	   Ext.getCmp('videoQualityBoxs').items.each(function(rec){
		   if(rec.checked) {
			   videoQuality |= rec.inputValue;
		   }
	   });
	   
	   var videoFrom;
	   Ext.getCmp('videoFromBoxs').items.each(function(rec){
		   if(rec.checked) {
			   videoFrom |= rec.inputValue;
		   }
	   });
	   
	   var mettingType;
	   Ext.getCmp('mettingTypeBoxs').items.each(function(rec){
		   if(rec.checked) {
			   mettingType |= rec.inputValue;
		   }
	   });
	   
	   var mettingStatus;
	   Ext.getCmp('mettingStatusBox').items.each(function(rec){
		   if(rec.checked) {
			   mettingStatus |= rec.inputValue;
		   }
	   });
	   
	   var channelCount = 0;
	   var createDateValue = Ext.getCmp('createDate').getValue();
	   var uid = Ext.getCmp('uid').getValue();
	  
	   if(uid) {
		   channelCount = Ext.getCmp('seqNum').getValue();
	   } else {
		    var rootNode = this.getChannelStore().getRootNode();
		    
		    Ext.Array.each(rootNode.childNodes, function(rec){
				   channelCount ++;
				   
				   channelCount += rec.childNodes.length;
			 });
	        channelCount += 1;
	   }
	   
	   var createDate;
	   if(createDateValue) {
		   createDate = new Date(createDateValue);
	   } else {
		   createDate = new Date();
	   }
	   
	    var win = button.up('window'),
	    form   = win.down('form');
	   	var obj = this;
	    form.submit({
		       	method:'post',
		        url: '/channel/ajaxUpdateChannel.action',
		        params:{
		        	'channel.relateCat':catUids.join(","),
		        	'channel.targetRole':targetRole,
		        	'channel.videoQuality':videoQuality,
		        	'channel.videoFrom':videoFrom, 
		        	'channel.mettingType':mettingType,
		        	'channel.mettingStatus':mettingStatus, 
		        	'channel.createDate':Ext.Date.format(createDate, 'Y-m-d H:i:s'),
		        	'channel.seqNum':channelCount
		        	},
	            success: function(form, action) {
		           	 win.close();
		           	 obj.reloadChannel();
	            },
	            failure: function(form, action) {
	           		Ext.Msg.alert("提示","更新失败，请重试！"); 
	            }
	    });
	  
   },

   uploadChannelPic:function(file, value, eOpts) {
	   var form = file.up('form');
       if(form.isValid()){
           form.submit({
               url: 'ajaxUploadFile.action',
               params:{dir:'channel'},
               waitMsg: '正在上传文件...',
               success: function(form, action) {
                   var path = action.result.result;
                   Ext.getCmp('picture').setValue(path);
                   Ext.getCmp('previewChannelPic').body.update('<img src="'+path+'" width="80" height="60"/>');
                   file.up('Channel-Edit').doLayout();
               },
               failure: function (form, action) {
                   Ext.Msg.alert('出错', action.result.msg);
               }
           });
       }
   },
   
   uploadChannelPlatePic:function(file, value, eOpts) {
	   var form = file.up('form');
       if(form.isValid()){
           form.submit({
               url: 'ajaxUploadFile.action',
               params:{dir:'channel'},
               waitMsg: '正在上传文件...',
               success: function(form, action) {
                   var path = action.result.result;
                   Ext.getCmp('platePicture').setValue(path);
                   Ext.getCmp('previewPlatePic').body.update('<img src="'+path+'" width="80" height="60"/>');
                   file.up('Channel-Edit').doLayout();
               },
               failure: function (form, action) {
                   Ext.Msg.alert('出错', action.result.msg);
               }
           });
       }
   },
   
   changeChannelPlate: function(obj, newValue, oldValue, eOpts) {
	   var oldSelectPlate;
	   var newSelectPlate;
	   if(oldValue) {
		   oldSelectPlate = Ext.get('plate'+oldValue);
		   if(oldSelectPlate) {
			   oldSelectPlate.setStyle('background','');
		   }
	   }
	   if(newValue){
		   newSelectPlate = Ext.get('plate'+newValue);
		   if(newSelectPlate) {
			   newSelectPlate.setStyle('background','#5CACEE');
		   }
	   }
   },
   
   changeChannelVideoType: function(obj, newValue, oldValue, eOpts) {
	   var videoType = Ext.get('video_type'+obj.inputValue);
	   if(newValue) {
		   if(videoType) {
 			   videoType.show();
 		   }
	   } else {
		   if(videoType) {
  			   videoType.hide();
  		   }
	   }
//	   obj.items.each(function (item) {
//		    var inputValue = item.inputValue;
//		    
//	        if (item.checked) {
//	        	videoType = Ext.get('video_type'+inputValue);
//	        	if(videoType) {
//	 			   videoType.show();
//	 		   }
//	        } else {
//	        	videoType = Ext.get('video_type'+inputValue);
//	        	if(videoType) {
//	  			   videoType.hide();
//	  		   }
//	        }
//	    });
	  var channelEdit = obj.up('Channel-Edit');
	  channelEdit.doLayout();
	  channelEdit.center();
   },
   
   changeChannelTargetRole: function(obj, newValue, oldValue, eOpts) {
		   var uiTypeSet = Ext.get('uiTypeSet');
		   var plateDistribution = Ext.get('plateDistribution');
		   var previewPlatePicPanel = Ext.get('previewPlatePicPanel');
		   if(obj.inputValue === 4) {
			   if(newValue) {
				   uiTypeSet.show();
				   plateDistribution.show();
				   previewPlatePicPanel.show();
			   } else {
				   uiTypeSet.hide();
				   plateDistribution.hide();
				   previewPlatePicPanel.hide();
			   }
			  var channelEdit = obj.up('Channel-Edit');
			  channelEdit.doLayout();
			  channelEdit.center();
		   }
   },
   
    deleteChannel: function(data) {
   	 var obj = this;
   	 Ext.MessageBox.confirm("注意", "您是否真的要删除本频道?您如果删除本频道，则与本频道关联的视频将无法在教育平台显示", function (btn) {
   		 if(btn === 'yes') {
   			 var ids = [];
   	    	 Ext.Array.each(data,function(record){  
   	             ids.push(record.get('uid'));  
   	         });  
   	         Ext.Ajax.request({  
   	             url:'/channel/ajaxDeleteChannel.action',  
   	             params:{uids:ids.join(",")},  
   	             method:'POST',  
   	             timeout:2000,  
   	             success:function(response,opts){  
   	             	obj.reloadChannel();
   	             }  
   	         });  
   		 }
   	 });
    },
    
   listAddChannelVideo:function(record) {
	   //var ChannelVideoAddWindow = Ext.widget('ChannelVideoAdd-Window');
	   var channelVideoAddWindow = Ext.widget('ChannelVideoAdd-Window');
	   var channelVideoAddStore = this.getChannelVideoAddStore();
	   
	   channelVideoAddStore.on('beforeload', function (store, options) {
           var new_params = {channelUid:record.get('uid')};
           Ext.apply(store.proxy.extraParams, new_params);
        });
	   Ext.getCmp('channelUid').setValue(record.get('uid'));
	   channelVideoAddWindow.setTitle('添加《'+record.get('name')+'》频道视频');
	   channelVideoAddStore.load();
	  // alert(record.get('uid')+"---------"+record.get('name'));
	   //channelVideoAddGrid.show();
	   //ChannelVideoAddWindow.child(channelVideoAddGrid);
	   //ChannelVideoAddWindow.doLayout();
   },
   
   listChannelVideo:function(record) {
	   //var ChannelVideoAddWindow = Ext.widget('ChannelVideoAdd-Window');
	   var channelVideoListWindow = Ext.widget('ChannelVideoList-Window');
	   var channelVideoListStore = this.getChannelVideoListStore();
	   
	   channelVideoListStore.on('beforeload', function (store, options) {
           var new_params = {channelUid:record.get('uid')};
           Ext.apply(store.proxy.extraParams, new_params);
        });
	   Ext.getCmp('channelUid').setValue(record.get('uid'));
	   channelVideoListWindow.setTitle('管理《'+record.get('name')+'》频道视频');
	   channelVideoListStore.load();
	  // alert(record.get('uid')+"---------"+record.get('name'));
	   //channelVideoAddGrid.show();
	   //ChannelVideoAddWindow.child(channelVideoAddGrid);
	   //ChannelVideoAddWindow.doLayout();
   },
   
   addChannelVideo:function(button) {
	   var channelVideoAddGrid = button.up('ChannelVideoAdd-Grid');
       var data = channelVideoAddGrid.getSelectionModel().getSelection(); 
       var me = this;
       if(data.length == 0){  
           Ext.Msg.alert("提示","请选择您要添加的视频!");  
       }else{ 
    	   var channelVideoAddStore = this.getChannelVideoAddStore();
   		   var ids = [];
       	   Ext.Array.each(data,function(record){  
                ids.push(record.get('uid'));  
            });
	       	Ext.Ajax.request({  
	            url:'/channel/ajaxAddChannelVideo.action',
	            params:{'videoUids':ids, 'uids':Ext.getCmp('channelUid').getValue()},
	            method:'POST',  
	            timeout:2000,  
	            success:function(response,opts){  
	            	Ext.MessageBox.confirm("确认", "添加频道视频成功！您是否继续添加频道视频？", function (btn) {
	            		if(btn === 'yes') {
	            			channelVideoAddStore.loadPage(1);
	            		} else {
	            			channelVideoAddGrid.up("window").close();
	            		}
	            	});
	            }  
	        });  
       }  
   },
   
   deleteMoreChannelVideo:function(button) {
	   var channelVideoListGrid = button.up('ChannelVideoList-Grid');
       var data = channelVideoListGrid.getSelectionModel().getSelection(); 
       var me = this;
       if(data.length == 0){  
           Ext.Msg.alert("提示","请选择您要删除的频道视频!");  
       }else{ 
    	   this.deleteChannelVideo(data);
       }  
   },
   
   deleteChannelVideo:function(data) {
	   var channelVideoListStore = this.getChannelVideoListStore();
	   var ids = [];
   	   Ext.Array.each(data,function(record){  
            ids.push(record.get('uid'));  
        });
   	    
   	Ext.MessageBox.confirm("提示", "您真的要删除频道视频？", function (btn) {
   		if(btn === 'yes') {
   			Ext.Ajax.request({  
   	            url:'/channel/ajaxDeleteChannelVideo.action',
   	            params:{'videoUids':ids, 'uids':Ext.getCmp('channelUid').getValue()},
   	            method:'POST',  
   	            timeout:2000,  
   	            success:function(response,opts){  
   	            	channelVideoListStore.loadPage(1);
   	            }  
   	        }); 
   		}
   	});
   },
   
   actionColumnOptChannelVideo:function(column, view, rowIndex, colIndex, item, e, record)  {
	   var channelVideoListStore = this.getChannelVideoListStore();
	   if(item.action === 'top') {
		   
		   var firstRecord = channelVideoListStore.first();
		   
		   var videoUids = [];
		   var seqNums = [];
		   
		   videoUids.push(firstRecord.get('uid'));
		   videoUids.push(record.get('uid'));
		   seqNums.push(record.get('seqNum'));
		   seqNums.push(firstRecord.get('seqNum'));
	   	   
		   Ext.Ajax.request({  
  	            url:'/channel/ajaxTopChannelVideo.action',
  	            params:{'videoUids':videoUids, 'uids':Ext.getCmp('channelUid').getValue(), 'seqNums':seqNums},
  	            method:'POST',  
  	            timeout:2000,  
  	            success:function(response,opts){  
  	            	channelVideoListStore.loadPage(1);
  	            }  
  	        }); 
	   } else if(item.action === 'recommend') {
	   		
		   Ext.Ajax.request({  
 	            url:'/channel/ajaxRecommentChannelVideo.action',
 	            params:{'videoUids':record.get('uid'), 'uids':Ext.getCmp('channelUid').getValue(), 'isHot':'Y'},
 	            method:'POST',  
 	            timeout:2000,  
 	            success:function(response,opts){  
 	            	channelVideoListStore.loadPage(1);
 	            }  
 	        }); 
		   
	   } else if(item.action === 'unrecommend') {
	   		
		   Ext.Ajax.request({  
 	            url:'/channel/ajaxRecommentChannelVideo.action',
 	            params:{'videoUids':record.get('uid'), 'uids':Ext.getCmp('channelUid').getValue(), 'isHot':'N'},
 	            method:'POST',  
 	            timeout:2000,  
 	            success:function(response,opts){  
 	            	channelVideoListStore.loadPage(1);
 	            }  
 	        }); 
		   
	   } else if(item.action === 'delete') {
		   this.deleteChannelVideo(record);
	   }
   },
   
   reloadChannel:function() {
	   	var contentPanel = this.getContentPanel();
	   	var channelStore = this.getChannelStore();
	   	contentPanel.removeAll(true);
	   	channelStore.load();
	    contentPanel.add(Ext.widget('Channel-Grid'));
	    if (contentPanel.floating) {
	  	   contentPanel.show();
	    }
   }
});